#include "MemoryManager.h"

#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

MemoryManager::MemoryManager(void)
{
    m_MemoryLevel = 1024;
}

MemoryManager::~MemoryManager(void)
{ 
    RECORDER::iterator it;
    vector<POINTER> addr;
    for (it = m_Recorder.begin(); it!= m_Recorder.end(); ++it)
    {
        addr.push_back(it->second.ptr);
    }
    for (UINT32 i = 0; i < addr.size(); ++i)
    {
        stringstream ss;
        ss << "Undeleted ptr @" << addr[i];
        m_Logger->log(m_MemoryLevel,
            Logger::WARNING,
            "MemoryManager::~MemoryManager()",
            ss.str()
            );
    }
}

VOID MemoryManager::regLogger(IN Logger* _log)
{
    m_Logger = _log;
}

VOID MemoryManager::setMemoryLevel(IN DOUBLE _lvl)
{
    m_MemoryLevel = _lvl;
}

VOID MemoryManager::logNew(IN POINTER _ptr, 
                           IN UINT32 _len, 
                           IN STRING _typeName, 
                           IN UINT32 _typeSize)
{   
    PtrKeeper pk;
    pk.ptr = _ptr;
    pk.length = _len;
    pk.typeSize = _typeSize;
    pk.typeName = _typeName;
    m_Recorder[_ptr] = pk;

    stringstream msg;
    msg << "New memory : ["
        << pk.typeName << " : "
        << pk.typeSize << "]*["
        << pk.length << "] @"
        << pk.ptr;
    m_Logger->log(m_MemoryLevel,
        Logger::NORMAL,
        "MemoryNew",
        msg.str());
}

VOID MemoryManager::logDelete(IN POINTER _ptr)
{
    PtrKeeper pk = m_Recorder.find(_ptr)->second;

    stringstream msg;
    msg << "Delete memory : ["
        << pk.typeName << " : "
        << pk.typeSize << "]*["
        << pk.length << "] @"
        << pk.ptr;
    m_Logger->log(m_MemoryLevel,
        Logger::NORMAL,
        "MemoryDelete",
        msg.str());
}

